# -*- coding: utf-8 -*-
# Author: xiantingDeng
# File: 06_生成器&迭代器&闭包.py
# Time: 11:19

# 迭代器
"""
# str1 ="hello"
# print(dir(str1)) # 获取对象的所有方法

# 判断一个对象是否可迭代

str = "hello"
print("__iter__" in dir(str))


list = [11,22,33]
# print("__iter__" in dir(list))


print("__iter__"and"__next__" in dir(list)) # 判断是否是迭代器

lis = [11,22,]
nex = iter(lis) # 将可迭代对象转换迭代器
print(next(nex))



lis = [11,22,33,44,55,66,77,88,99,14,12,15]

obj = iter(lis)
while True:
    try:
        print(next(obj))
    except StopIteration: # 循环取值，如果报StopIteration异常则break
        break

"""

# 生成器

# def func():
#     print(11)
#     yield 22
#
# ret = func()
# print(ret.__next__())


# def func():
#     print(123)
#     print(666)
#     yield 222
#     a = 1
#     b = 2
#     c = a + b
#     print(c)
#     yield 88
#
# ret = func()
# print(next(ret))
# print(next(ret))
# 吃包子练习
# def eat():
#     lst = []
#     for i in range(1, 1000):
#         lst.append('包子' + str(i))
#     return lst
#
#
# e = eat()
# print(e)

# def eat():
#     for i in range(1,1000):
#         yield "baozi"+ str(i)
#
# e = eat()
# for i in range(200):
#     next(e)

# yield from 会把这个迭代对象的每个元素当成迭代器的每个结果进行返回
"""
def func():
    lis = [1,2,3,4,5]
    yield lis

ret = func()
print(next(ret))

def func():
    l1 = [1, 2, 3, 4, 5]
    yield from l1

ret = func()
print(ret)
# 他会将这个可迭代对象(列表)的每个元素当成迭代器的每个结果进行返回。
for i in range(5):
    print(next(ret))
"""


# 闭包

def func():
    a = 1

    def inner():
        print(a)

    return inner


ret = func()
# 是闭包e

# 不是闭包
a = 2
def func():
    def inner():
        print(a)
    return inner
ret = func()

# 如何判断是闭包
print(ret.__code__.co_freevars)